package com.huihuiyun.huihuiyun.server.controller.manager.website.authorize;

import com.huihuiyun.huihuiyun.server.ApplicationConst;
import com.huihuiyun.huihuiyun.server.domain.HhyManager;
import com.huihuiyun.huihuiyun.server.service.MockRedisService;
import com.huihuiyun.huihuiyun.server.viewobject.ResultVO;
import com.huihuiyun.huihuiyun.server.viewobject.ResultVOUtil;
import com.mark.util.CommonUtil;
import com.mark.util.CookieUtil;
import com.mark.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;

@Component
@Slf4j
public class ManagerWebsiteAuthorizeHandler {
    @Autowired
    private MockRedisService mockRedisService;

    public HhyManager getHhyManager(HttpServletRequest httpServletRequest) {
        HhyManager hhyManager = null;
        try {
            if (httpServletRequest == null) {
                return null;
            }
            String token = CookieUtil.get(httpServletRequest, ApplicationConst.token);
            if (token == null) {
                return null;
            }
            String json = mockRedisService.get(token);
            if (json == null) {
                return null;
            }
            hhyManager = JsonUtil.json2Bean(json, HhyManager.class);
        } catch (Exception e) {
            log.error("", e);
        }
        return hhyManager;
    }

    public void afterLoginSuccess(HttpServletResponse httpServletResponse, HhyManager hhyManager) {
        try {
            String token = ApplicationConst.token + "_" + CommonUtil.createRandom32String();
            String json = JsonUtil.bean2Json(hhyManager);
            mockRedisService.set(token, json);
            CookieUtil.set(httpServletResponse, ApplicationConst.token, token, 600);
        } catch (Exception e) {
            log.error("", e);
        }
    }

    public Response createNoAuthorizedResponse() {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }

    public ResultVO createNoAuthorizedResultVO(HttpServletResponse httpServletResponse) {
        httpServletResponse.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
        return ResultVOUtil.error("未登录");
    }
}